/*
 * 日照善成信息技术有限公司 版权所有
 */
package helper;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import helper.util.RandomNumberUtil;
import jodd.io.FileNameUtil;
import play.Logger;
import play.libs.MimeTypes;
import utils.DateUtil;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * Aliyun OSS文件上传工具.
 */
public class AliyunOssUploader {

    private static OSSClient ossClient = new OSSClient(GlobalConfig.ALI_OSS_ENDPOINT, GlobalConfig.ALI_OSS_ACCESS_KEY_ID, GlobalConfig.ALI_OSS_ACCESS_KEY_SECRET);



    /**
     * 上传文件到OSS公共文件.
     * @param file
     * @return OSS Object Name
     */
    public static String uploadPublicFile(File file) {
        try {
            String bucketName = GlobalConfig.ALI_OSS_BUCKET_NAME;
            InputStream content = new FileInputStream(file);
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            // 必须设置ContentLength
            meta.setContentLength(file.length());

            String mimeType = MimeTypes.getContentType(file.getName());

            meta.setContentType(mimeType);

            String fileExt = FileNameUtil.getExtension(file.getName());


            String dateString = DateUtil.dateToString(new Date(), "yyyyMMdd");
            String objectName = "u/" + dateString + "/" + RandomNumberUtil.generateRandomChars(16) + "." + fileExt;

            // 上传Object.
            PutObjectResult result = ossClient.putObject(bucketName, objectName, content, meta);

            // 打印ETag
            Logger.info("LOG01730: upload file " + file.getName() + " result etag:" + result.getETag());
            Logger.info("LOG01731: upload file cdnUrlPrefix objectName:" + objectName);

            BufferedImage sourceImg = ImageIO.read(new FileInputStream(file));
            Integer imgWidth = sourceImg.getWidth();
            // 判断宽度是否大于 size  如果大于 则返回 size 宽度。 否则 返回原宽度
            return GlobalConfig.ASSETS_BASE_URL + "/" + objectName;
        } catch (IOException e) {
            Logger.warn(e, "LOG01750: upload file to OSS failed!");
            return null;
        }
    }


    /**
     * 上传文件到OSS公共文件.
     * @param file
     * @return OSS Object Name
     */
    public static String uploadPublicFile(File file , Integer size) {
        try {
            String bucketName = GlobalConfig.ALI_OSS_BUCKET_NAME;
            InputStream content = new FileInputStream(file);
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            // 必须设置ContentLength
            meta.setContentLength(file.length());

            String mimeType = MimeTypes.getContentType(file.getName());
            meta.setContentType(mimeType);

            String fileExt = FileNameUtil.getExtension(file.getName());


            String dateString = DateUtil.dateToString(new Date(), "yyyyMMdd");
            String objectName = "u/" + dateString + "/" + RandomNumberUtil.generateRandomChars(16) + "." + fileExt;

            // 上传Object.
            PutObjectResult result = ossClient.putObject(bucketName, objectName, content, meta);

            // 打印ETag
            Logger.info("LOG01730: upload file " + file.getName() + " result etag:" + result.getETag());
            Logger.info("LOG01731: upload file cdnUrlPrefix objectName:" + objectName);

            BufferedImage sourceImg = ImageIO.read(new FileInputStream(file));
            Integer imgWidth = sourceImg.getWidth();
            // 判断宽度是否大于 size  如果大于 则返回 size 宽度。 否则 返回原宽度
            if(imgWidth > size) {
                return GlobalConfig.ASSETS_BASE_URL +"/" + objectName;
            } else {
                return GlobalConfig.ASSETS_BASE_URL + "/" + objectName;
            }
        } catch (IOException e) {
            Logger.warn(e, "LOG01750: upload file to OSS failed!");
            return null;
        }
    }


    /**
     * 上传文件到OSS公共文件.
     * @param file
     * @param projectName  项目的名字. OSS 中存放格式    http;//cdn.ulmsale.net/weixin/20160602/xxxxxxxxxx.jpg
     * @return OSS Object Name
     */
    public static String uploadPublicFile(File file , Integer size , String projectName) {
        try {
            String bucketName = GlobalConfig.ALI_OSS_BUCKET_NAME;
            InputStream content = new FileInputStream(file);
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            // 必须设置ContentLength
            meta.setContentLength(file.length());

            String mimeType = MimeTypes.getContentType(file.getName());
            meta.setContentType(mimeType);

            String fileExt = FileNameUtil.getExtension(file.getName());


            String dateString = DateUtil.dateToString(new Date(), "yyyyMMdd");
            String objectName = projectName +"/" + dateString + "/" + RandomNumberUtil.generateRandomChars(16) + "." + fileExt;

            // 上传Object.
            PutObjectResult result = ossClient.putObject(bucketName, objectName, content, meta);

            // 打印ETag
            Logger.info("LOG01730: upload file " + file.getName() + " result etag:" + result.getETag());
            Logger.info("LOG01731: upload file cdnUrlPrefix objectName:" + objectName);

            BufferedImage sourceImg = ImageIO.read(new FileInputStream(file));
            Integer imgWidth = sourceImg.getWidth();

            // 判断宽度是否大于 size  如果大于 则返回 size 宽度。 否则 返回原宽度
            if(imgWidth > size) {
                return GlobalConfig.ASSETS_BASE_URL +"/" + objectName + "@"+size+"w";
            } else {
                return GlobalConfig.ASSETS_BASE_URL + "/" + objectName + "@"+imgWidth+"w";
            }

        } catch (IOException e) {
            Logger.warn(e, "LOG01750: upload file to OSS failed!");
            return null;
        }
    }



    /**
     * 上传文件到OSS公共文件.
     * @param file
     * @param projectName  项目的名字. OSS 中存放格式    http;//cdn.ulmsale.net/weixin/20160602/xxxxxxxxxx.jpg
     * @return OSS Object Name
     */
    public static String uploadFile(File file , String projectName) {
        try {
            String bucketName = GlobalConfig.ALI_OSS_BUCKET_NAME;
            InputStream content = new FileInputStream(file);
            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();
            // 必须设置ContentLength
            meta.setContentLength(file.length());

            String mimeType = MimeTypes.getContentType(file.getName());
            meta.setContentType(mimeType);

            String fileExt = FileNameUtil.getExtension(file.getName());


            String dateString = DateUtil.dateToString(new Date(), "yyyyMMdd");
            String objectName = projectName +"/" + dateString + "/" + RandomNumberUtil.generateRandomChars(16) + "." + fileExt;

            // 上传Object.
            PutObjectResult result = ossClient.putObject(bucketName, objectName, content, meta);

            // 打印ETag
            Logger.info("LOG01730: upload file " + file.getName() + " result etag:" + result.getETag());
            Logger.info("LOG01731: upload file cdnUrlPrefix objectName:" + objectName);

            return GlobalConfig.ASSETS_BASE_URL +"/" + objectName;
//            BufferedImage sourceImg = ImageIO.read(new FileInputStream(file));
//            Integer imgWidth = sourceImg.getWidth();
//
//            // 判断宽度是否大于 size  如果大于 则返回 size 宽度。 否则 返回原宽度
//            if(imgWidth > size) {
//                return GlobalConfig.ASSETS_BASE_URL +"/" + objectName + "@"+size+"w";
//            } else {
//                return GlobalConfig.ASSETS_BASE_URL + "/" + objectName + "@"+imgWidth+"w";
//            }

        } catch (IOException e) {
            Logger.warn(e, "LOG01750: upload file to OSS failed!");
            return null;
        }
    }


    /**
     * 上传文件到OSS公共文件.
     *
     * @param fileName
     * @param fileLength
     * @return OSS Object Name
     */
    public static String uploadPublicFile(InputStream in, String fileName, long fileLength) {
        try {
            String bucketName = GlobalConfig.ALI_OSS_BUCKET_NAME;

            // 创建上传Object的Metadata
            ObjectMetadata meta = new ObjectMetadata();

            // 必须设置ContentLength
            meta.setContentLength(fileLength);

            String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1);
            String dateString = DateUtil.dateToString(new Date(), "yyyyMMdd");
            String objectName = "rizhi/" + dateString + "/" + RandomNumberUtil.generateRandomChars(16) + "." + fileExt;

            // 上传Object.
            PutObjectResult result = ossClient.putObject(bucketName, objectName, in, meta);

            // 打印ETag
            Logger.info("LOG01730: upload file " + fileName + " result etag:" + result.getETag());
            Logger.info("LOG01731: upload file cdnUrlPrefix objectName:" + objectName);

            //BufferedImage sourceImg = ImageIO.read(in);
            //Integer imgWidth = sourceImg.getWidth();
            // 判断宽度是否大于 size  如果大于 则返回 size 宽度。 否则 返回原宽度
            return GlobalConfig.ASSETS_BASE_URL + "/" + objectName;
        } catch (Exception e) {
            Logger.warn("LOG01750: upload file to OSS failed!");
            return null;
        }
    }
}
